import type { LoopSwitchGroupDataItemType } from './typings'
import { defineComponent, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElLink,
  ElInput,
  ElSpace,
  ElTooltip,
  ElScrollbar,
  ElAlert,
  ElEmpty,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import LoopSwitchGroupModal from '../components/LoopSwitchGroupModal'
import SaasTitle from '~/components/SaasTitle'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from './index.module.scss'

// 本页面默认分组是写死的
export default defineComponent(function LoopSwitchGroupTree() {
  const store = useStore()
  const searchGroupNameRef = ref<string>()
  const recordRef = ref<LoopSwitchGroupDataItemType>()
  const loopGroupListRef = ref<LoopSwitchGroupDataItemType[]>([])
  const userState = useVuexGetters('user', ['permission'])
  const loopSwitchGroupState = useVuexGetters('loopSwitchGroup', [
    'defaultLoopGroup',
    'activeLoopGroupId'
  ])

  // 切换选中的分组
  const handleChangeActiveloopGroup = (id?: string) => {
    store.commit('loopSwitchGroup/SET_ACTIVE_LOOP_GROUP_ID', id)
  }

  // 查询分组列表
  const handleSearchLoopGroupList = async () => {
    const params = { ident: 'hardware' }
    const res = await store.dispatch('loopSwitchGroup/GetMonitorLoopSwitchGroupList', params)
    loopGroupListRef.value = res?.data || []
    handleChangeActiveloopGroup(loopGroupListRef.value?.[0]?.id)
  }

  // 切换新增修改弹框
  const handleChangeLoopSwitchGroupOptionModal = (record?: LoopSwitchGroupDataItemType) => {
    recordRef.value = record
    // 关闭弹框则查询新列表
    if (!record) handleSearchLoopGroupList()
  }

  // 删除回路分组
  const handleDeleteLoopSwitchGroup = (record?: LoopSwitchGroupDataItemType) => {
    ElMessageBox({
      title: '确认提示',
      message: '确认删除分组？',
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        const res = await store.dispatch('loopSwitchGroup/DeleteMonitorLoopSwitchGroupInfo', {
          ids: record?.id
        })
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleSearchLoopGroupList()
        }
      })
      .catch(() => {})
  }

  // 按下回车后查询分组列表
  const handleSearchLoopGroupListByGroupName = (e: Event | KeyboardEvent) => {
    if ((e as KeyboardEvent).key !== 'Enter') return
    loopGroupListRef.value = loopGroupListRef.value.filter((item: LoopSwitchGroupDataItemType) => {
      return item.groupName?.indexOf(searchGroupNameRef.value || '') !== -1
    })
  }

  onMounted(() => {
    handleSearchLoopGroupList()
  })

  return () => (
    <ElCard
      class={styles['loop-group-tree']}
      v-slots={{
        header: () => (
          <section class={styles['loop-group-tree-header']}>
            <SaasTitle type="primary">分组列表</SaasTitle>
            {userState.permission.value.has('monitor_task_taskgroup_add') && (
              <ElLink
                underline={false}
                icon={Plus}
                onClick={() => handleChangeLoopSwitchGroupOptionModal({})}
              />
            )}
          </section>
        )
      }}
    >
      <ElInput
        v-model={searchGroupNameRef.value}
        prefixIcon={<AliIcon type="icon-sousuo" />}
        clearable
        placeholder="分组名称 回车搜索"
        onKeydown={handleSearchLoopGroupListByGroupName}
        onClear={handleSearchLoopGroupList}
      />
      {loopGroupListRef.value?.length ? (
        <ElScrollbar class={styles['loop-group-tree-scrollball']}>
          <ElSpace wrap fill class={styles['loop-group-tree-space']}>
            {loopGroupListRef.value?.map((item) => (
              <ElAlert
                class={{
                  [styles['loop-group-tree-alert']]: true,
                  [styles['loop-group-tree-active-alert']]:
                    loopSwitchGroupState?.activeLoopGroupId?.value === item?.id
                }}
                closable={false}
                v-slots={{
                  title: () => (
                    <section class={styles['loop-group-tree-alert-title']}>
                      <ElTooltip content={item.groupName} placement="top">
                        <span class="text-one-line-overflow">{item.groupName}</span>
                      </ElTooltip>
                      {item?.id && (
                        <ElSpace size={0} class={styles['loop-group-tree-alert-btns']}>
                          {userState.permission.value.has('monitor_task_taskgroup_update') && (
                            <ElLink
                              type="primary"
                              underline={false}
                              icon={<AliIcon type="icon-bianji" />}
                              onClick={() => handleChangeLoopSwitchGroupOptionModal(item)}
                            />
                          )}
                          {userState.permission.value.has('monitor_task_taskgroup_remove') && (
                            <ElLink
                              type="primary"
                              underline={false}
                              icon={<AliIcon type="icon-shanchu" />}
                              onClick={() => handleDeleteLoopSwitchGroup(item)}
                            />
                          )}
                        </ElSpace>
                      )}
                    </section>
                  )
                }}
                {...{ onClick: () => handleChangeActiveloopGroup(item.id!) }}
              />
            ))}
          </ElSpace>
        </ElScrollbar>
      ) : (
        <ElEmpty description="未匹配到数据" />
      )}

      {recordRef.value && (
        <LoopSwitchGroupModal
          visible={!!recordRef.value}
          detail={recordRef.value}
          cancel={() => handleChangeLoopSwitchGroupOptionModal()}
        />
      )}
    </ElCard>
  )
})
